package com.example.glide_test.request;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import java.lang.ref.SoftReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class BitmapRequest {
    private Context context;
    private String url;
    private SoftReference<ImageView> imageView;
    private RequestListener requestListener;
    //请求标识  防止之后图片加载错位
    private String urlMD5;
    //占位图片id
    private int resId;

    public BitmapRequest(Context context) {
        this.context = context;
    }
    //链式调用  通过链条的方式初始化对象
    public BitmapRequest load(String url){
        this.url = url;
        urlMD5 = md5(url);
        return this;
    }
    public BitmapRequest loading(int resId){
        this.resId = resId;
        return this;
    }
    public BitmapRequest listener(RequestListener requestListener){
        this.requestListener = requestListener;
        return this;
    }
    public void into(ImageView imageView){
        imageView.setTag(urlMD5);
        this.imageView = new SoftReference<>(imageView);
        RequestManager.getInstance().addBitmapRequest(this);
    }

    public int getResId() {
        return resId;
    }

    public ImageView getImageView() {
        return imageView.get();
    }

    public String getUrlMD5() {
        return urlMD5;
    }

    public String getUrl() {
        return url;
    }

    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
